﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Models.PDA;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.IdentityModel.Logging;
using NetTaste;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using NPOI.XWPF.UserModel;
using Org.BouncyCastle.Asn1.X509;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using static NPOI.HSSF.Util.HSSFColor;

namespace DFGK_WMS.Repository
{
    internal class TOutboundOrderDetailRepository : BaseRepository<TShippingOrderDetail>, ITOutboundOrderDetailRepository
    {
        public TOutboundOrderDetailRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        #region 基础接口
        /// <summary>
        /// 获取出库单明细表数据
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public TShippingOrderDetail GetShippingOrderDetail(int OrderId)
        {
            var list = Context.TShippingOrderDetails
                .Where(x => x.Id == OrderId)
                .FirstOrDefault();

            return list;

        }

        /// <summary>
        /// 获取出库站台
        /// </summary>
        /// <param name="WhId"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public List<TStation> GetStation(int WhId)
        {
            var station = Context.TStations
                .Where(p => p.WhId == WhId && p.Status == 2)
                .ToList();
            if (station == null)
            {
                return null;
            }
            return station;
        }

        /// <summary>
        /// 获取出库单明细  多个物料版本
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="isNetWork">0没网 1有网</param>
        /// <returns></returns>
        public List<TShippingOrderDetailPlusDTOGroup> GetTShippingOrderDetailPlus(int pageIndex, int pageSize,int isNetWork)
        {
            var list = Context.TShippingOrderDetails.AsEnumerable().Where(s=>s.Status==0).OrderByDescending(s=>s.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).GroupBy(s=>s.OrderSn);
            
            List<TShippingOrderDetailPlusDTOGroup> resList = new List<TShippingOrderDetailPlusDTOGroup>();
            foreach (var item in list)
            {
                var key = item.Key;
                var lockCellList = new List<TShippingLockCell>();
                foreach (var value in item)
                {
                    var lockCell = Context.TShippingLockCells.Where(s=>s.OrderDetailId==value.Id && s.IsPicking==false).ToList();
                    if (isNetWork == 0)
                    {
                        lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == value.Id && 
                        s.IsPicking == false && s.AreaCode=="A04").ToList();
                    }
                    if (lockCell != null && lockCell.Count() > 0)
                    {
                        foreach (var item1 in lockCell)
                        {
                            lockCellList.Add(item1);
                        }
                    } 
                }
                if (lockCellList != null && lockCellList.Count() > 0)
                {
                    resList.Add(new TShippingOrderDetailPlusDTOGroup(key, lockCellList));
                }
            }
            return resList;

        }

      
        // 根据托盘条码号查询库存表
        public TInventory GetInventory(string PalletBarcode)
        {
            var list = Context.TInventories
                .FirstOrDefault(x => x.PalletBarcode == PalletBarcode);

            if (list == null)
            {
                return null;
            }
            return list;
        }

        
       
        /// <summary>
        /// 首次提交，更新库存中状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int UpdStatus(int id)
        {
            int count = 0;
            var inventory = Context.TInventory.FirstOrDefault(x => x.MaterialId == id);
            if (inventory != null)
            {
                inventory.Status = 4;

                inventory.IsLock = inventory.IsLock.HasValue ? (bool)inventory.IsLock : false;

                count = count += 1;

                // 提交对数据库的更改
                Context.SaveChanges();
            }
            else
            {
                return 0;
            }
            return count;
        }


        /// <summary>
        /// 根据ID查询入库垛信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TStackingStorage> GetStackingStorages(string[] PalletBarcode)
        {
            var list = new List<TStackingStorage>();
            foreach (var item in PalletBarcode)
            {
                var staSto = Context.TStackingStorages.Where(x => x.PalletBarcode == item);
                if (staSto != null)
                {
                    list.AddRange(staSto);
                }
            }
            return list.ToList();
        }

        

        /// <summary>
        /// 拣选出库
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPickingOutbound(TPickingStationDatum item)
        {
            TPickingStationDatum pickingStationDatum = new TPickingStationDatum();
            pickingStationDatum.child = new List<TPickingStationDataDetail>();

            var addedItem = Context.TPickingStationData.Add(item);
            Context.SaveChanges();

            if (addedItem != null)
            {
                int newPickingStationDataId = addedItem.Entity.Id;

                TPickingStationDataDetail pickingStationDataDetail = new TPickingStationDataDetail();
                pickingStationDataDetail.PickingStationDataId = newPickingStationDataId;

                pickingStationDataDetail.PickingStationDataId = newPickingStationDataId;
                pickingStationDataDetail.StationId = item.child[0].StationId;
                pickingStationDataDetail.StationCode = item.child[0].StationCode;
                pickingStationDataDetail.PackageBarcode = item.child[0].PackageBarcode;
                pickingStationDataDetail.Barcode = item.child[0].Barcode;
                pickingStationDataDetail.SkuNum = item.child[0].SkuNum;
                pickingStationDataDetail.IsSku = item.child[0].IsSku;
                pickingStationDataDetail.IsSelected = item.child[0].IsSelected;
                pickingStationDataDetail.PickedNum = item.child[0].PickedNum;
                pickingStationDataDetail.BarcodeRange = item.child[0].BarcodeRange;

                Context.TPickingStationDataDetails.Add(pickingStationDataDetail);

                // 再次保存以关联TPickingStationData和TPickingStationDataDetail之间的关系
                Context.SaveChanges();

                return true;
            }

            return false;
        }


        /// <summary>
        /// 获取拣选出库详情
        /// </summary>
        /// <param name="PickingStationDataId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TPickingStationDataDetail> GetPickingStationDetail(int PickingStationDataId)
        {
            var list = Context.TPickingStationDataDetails
                .Where(x => x.PickingStationDataId == PickingStationDataId);

            return list.ToList();
        }

        /// <summary>
        /// 获取库存数量
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public decimal GetInventoryQuantity(int? MaterialId)
        {
            var Qty = Context.TInventories
                .Where(x => x.MaterialId == MaterialId)
                .Select(x => x.AvailableQty).Sum();
            if (Qty > 0)
            {
                return Qty.Value;
            }
            return 0;
        }

        /// <summary>
        /// 减去库存数量并修改库存状态
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool GetDwindleNumbers(TInventory upd, decimal? num)
        {
            if (upd == null)
            {
                return false;
            }
            upd.AvailableQty = upd.AvailableQty - num;
            upd.Status = 1;

            Context.SaveChanges();

            return true;

        }


        /// <summary>
        /// 查询指令记录
        /// </summary>
        /// <param name="criteria"></param>
        /// <param name="shippingOrderDetail"></param>
        /// <returns></returns>
        public List<TInstruct> GetInstructsCount(InstructCriteriaModel criteria, TShippingOrderDetail shippingOrderDetail)
        {
            var list = Context.TInstructs.AsQueryable();

            list = list.Where(t => t.InstructType == 2 && t.Status == 2);

            return list.ToList();
        }


        /// <summary>
        /// 查询定时任务
        /// </summary>
        /// <param name="RecordId"></param>
        /// <returns></returns>
        public bool ValidScheduledTaskData(int RecordId)
        {
            var list = Context.TScheduledTasks
                .Where(x => x.RecordId == RecordId && x.RecordType == 2);

            if (list == null)
            {
                return false;
            }

            return true;
        }

        // 插入日志
        public int InsertLog(TLog log)
        {
            try
            {
                Context.TLogs.Add(log);
                Context.SaveChanges();
                return 1;
            }
            catch
            {
                return -1;
            }
        }

        // 更新计划任务
        public int InsertScheduledTask(TScheduledTask item)
        {
            try
            {
                Context.TScheduledTasks.Add(item);

                return Context.SaveChanges();
            }
            catch { return -1; }
        }

        // 根据ID获取

        // 根据单号查询出库单明细数据并修改状态
        public bool UpdateShippingOrderDetail(int id)
        {
            var list = Context.TShippingOrderDetails
                .Where(x => x.Id == id)
                .FirstOrDefault();
            if (list == null)
            {
                return false;
            }
            list.IsOutOrderReview = false;
            return true;

        }

        // 更新库房信息
        public bool UpdInstructsCount(TShippingOrderDetail shippingOrderDetail)
        {
            var list = Context.TInstructs.FirstOrDefault();
            list.WarehouseCode = shippingOrderDetail.WarehouseCode;
            list.Status = 2;
            if (list != null)
            {
                return true;
            }
            return false;
        }

        // 获取入库垛信息
        public TStackingStorage GetStackingStorage(string PalletBarcode)
        {
            var list = Context.TStackingStorages
                .Where(x => x.PalletBarcode == PalletBarcode)
                .FirstOrDefault();

            return list;
        }

        // 获取入库垛信息及状态
        public TStackingStorage GetStackingStorageStatus(string PalletBarcode, int status)
        {
            var list = Context.TStackingStorages
                .Where(x => x.PalletBarcode == PalletBarcode && x.Status == status)
                .FirstOrDefault();

            return list;
        }

        // 获取仓位信息
        public TCell GetInventoryByTCell(string palletBarcode)
        {
            TInventory inventoryModel = GetInventory(palletBarcode);

            if (inventoryModel == null)
            {
                return null;
            }

            var cell = Context.TCells.Where(x => x.Code == inventoryModel.LocationCode).FirstOrDefault();
            return cell;

        }

        // 更新仓位信息
        public bool UpdateCell(TCell tcell)
        {
            try
            {
                if (tcell == null)
                {
                    return false;
                }
                tcell.FullStatus = 0;
                tcell.IsLock = false;
                tcell.BusinessType = 0;
                tcell.ModifyDate = DateTime.Now;
                tcell.Status = 1;

                return true;
            }
            catch
            {
                return false;
            }

        }

        // 更新垛主表的状态为失效状态
        public bool UpdateStackingStorage(TStackingStorage model)
        {
            var list = Context.TStackingStorages
                .Where(x => x.Id == model.Id)
                .FirstOrDefault();

            if (list == null)
            {
                return false;
            }
            list.Status = 0;
            list.ModifyDate = DateTime.Now;
            Context.SaveChanges();
            return true;
        }

        // 删除库存表数据
        public bool DeleteInventory(int id)
        {
            try
            {
                var list = Context.TInventories.FirstOrDefault(x => x.Id == id);
                if (list == null)
                {
                    return false;
                }
                Context.TInventories.Remove(list);
                Context.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region 执行出库单
        /// <summary>
        /// 执行出库单
        /// </summary>
        /// <param name="opUser"></param>
        /// <param name="id"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool RunShippingOrderDetail(int id, TShippingOrderDetail shippingOrderDetail, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    if (id <= 0)
                    {
                        message = "请求参数有误，请检查请求参数";
                        return false;
                    }
                    bool result = false;


                    var list = GetInstructsCount(new InstructCriteriaModel
                    {
                        WarehouseCode = shippingOrderDetail.WarehouseCode,
                        Status = 2,
                    }, shippingOrderDetail);

                    if (list.Count > 0)
                    {
                        message = "存在盘点任务未完成";
                        tran.Rollback();
                        return false;
                    }
                    if (UpdStatus(shippingOrderDetail.MaterialId) <= 0)
                    {
                        message = "更新库存状态失败";
                        tran.Rollback();
                        return false;
                    }
                    TShippingOrderDetail shippingOrderDetailModel = GetShippingOrderDetail(id);
                    shippingOrderDetailModel.Status = (int)EmBillStatus.Executing;
                    shippingOrderDetailModel.ModifyDate = DateTime.Now;
                    shippingOrderDetailModel.ModifyUserId = shippingOrderDetail.CreateUserId;
                    shippingOrderDetailModel.ModifyUserName = shippingOrderDetail.ModifyUserName;


                    //if (ValidScheduledTaskData(shippingOrderDetail.Id))
                    //{
                    //   tran.Rollback();
                    //    return false;
                    // }

                    result = InsertScheduledTask(new TScheduledTask
                    {
                        RecordType = 2,
                        RecordId = shippingOrderDetail.Id,
                        WarehouseId = shippingOrderDetail.WarehouseId,
                        WarehouseName = shippingOrderDetail.WarehouseName,
                        WarehouseCode = shippingOrderDetail.WarehouseCode,
                        Priority = (shippingOrderDetail.IsOnceOut.HasValue && shippingOrderDetail.IsOnceOut.Value) ? 999 : 0,
                        RefId = null,
                        Data = null,
                        Status = 0,
                        Title = "出库任务启动",
                        CreateDate = DateTime.Now,
                        CreateUserId = shippingOrderDetail.CreateUserId,
                        CreateUserName = shippingOrderDetail.CreateUserName,
                    }) > 0;
                    if (!result)
                    {
                        message = "出库任务启动失败";
                        tran.Rollback();
                        return false;
                    }

                    result = InsertLog(new TLog
                    {
                        LogType = 1,
                        ActionType = 0,
                        RecordType = 2,
                        RecordId = id,
                        Status = 1,
                        CreateDate = DateTime.Now,
                        UserId = shippingOrderDetail.CreateUserId,
                        UserName = shippingOrderDetail.CreateUserName,
                        RealName = shippingOrderDetail.ModifyUserName,
                        ModuleName = "出库单",
                        Description = shippingOrderDetail.ModifyUserName + "执行了出库单" + shippingOrderDetail.OrderSn
                    }) > 0;
                    if (!result)
                    {
                        message = "保存失败";
                        tran.Rollback();
                        return false;
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return false;
                }
            }

        }

        #endregion


        #region 出库复核
        /// <summary>
        /// 出库复核
        /// </summary>
        /// <param name="OrderDTO"></param>
        /// <returns></returns>
        public bool SubmitOutInventoryReview(SubmitOutListDTO OrderDTO, out string message)
        {
            message = "";
            try
            {
                if (OrderDTO.orderDetId <= 0)
                {
                    message = "参数传递错误：orderDetId不可小于0";
                    return false;
                }

                bool result = false;
                {
                    TShippingOrderDetail shippingOrderDetail = GetShippingOrderDetail(OrderDTO.orderDetId);
                   
                    int logId = InsertLog(new TLog
                    {
                        LogType = 1,
                        ActionType = 0,
                        RecordType = 0,
                        RecordId = OrderDTO.orderDetId,
                        Status = 1,
                        CreateDate = DateTime.Now,
                        UserId = OrderDTO.createUserld,
                        UserName = OrderDTO.createUser,
                        RealName = OrderDTO.nowUserRealName,
                        ModuleName = "出库复核",
                        Description = string.Format("出库复核【{0}】,数量【{1}】，操作人{2}", shippingOrderDetail.WarehouseName, shippingOrderDetail.Qty, OrderDTO.nowUserRealName),
                    });
                    result = logId > 0;
                    if (!result)
                    {
                        message = "出库复核失败";
                        Context.Add(new TLog()
                        {
                            LogType = 1,
                            ActionType = 4,
                            Description="出库复核失败原因：添加出库复核日志失败",
                            CreateDate=DateTime.Now,
                        });
                        Context.SaveChanges();
                        return false;
                    }

                    
                    //更新复核状态
                    result = UpdateShippingOrderDetail(OrderDTO.orderDetId);
                    if (!result)
                    {
                        message = "更新复核状态失败";
                        Context.Add(new TLog()
                        {
                            LogType = 1,
                            ActionType = 6,
                            Description = "出库复核：更新出库单复核状态失败",
                            CreateDate = DateTime.Now,
                        });
                        Context.SaveChanges();
                        return false;
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                Context.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = "出库复核catch："+ex.Message,
                    CreateDate = DateTime.Now,
                });
                Context.SaveChanges();
                return false;
            }
        }

        #endregion

 
        // 查询托盘条码,并根据托盘条码查询其他信息
        public List<CreateOutboundOrderDTO> GetPalletBarcodePDA(int OrderDetailId)
        {
            var lockCellList = Context.TShippingLockCells.Where(x => x.OrderDetailId == OrderDetailId).Select(s => new CreateOutboundOrderDTO()
            {
                DeliveryOrderID = s.OrderDetailId.GetValueOrDefault(),
                CellCode = s.CellCode,
                PalletBarcode = s.PalletBarcode,
                MaterialsId = s.MaterialId.GetValueOrDefault(),
                MaterialCode = s.MaterialCode,
                BatchNo = s.BatchNo,
                InventoryQty = s.InventoryQty.GetValueOrDefault(),
                OutQty = s.OutQty.GetValueOrDefault()
            });

            List<CreateOutboundOrderDTO> Outbound = lockCellList.ToList();
            return Outbound;
        }

        
        public bool ChukuMsg(SubmitOutListDTONoNet OrderDTO, out string errorMsg,out List<TLog> logs)
        {
            errorMsg = string.Empty;
            logs= new List<TLog>();
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    // 出库复核 修改出库单为复核 和已完成
                    var shippingOrder = Context.TShippingOrderDetails.FirstOrDefault(s => s.Id == OrderDTO.orderDetId);
                    if (shippingOrder != null)
                    {
                        shippingOrder.IsOutOrderReview = true;
                        shippingOrder.Status = 4;
                        Context.Update(shippingOrder);
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "修改出库单为复核失败";
                            logs.Add(new TLog()
                            {
                                ActionType = 6,
                                CreateDate = DateTime.Now,
                                Description = "修改出库单为复核失败",
                                LogType = 1,
                            });
                            return false;
                        }
                    }
                    else
                    {
                        tran.Rollback();
                        errorMsg = "查询不到的出库单id为"+OrderDTO.orderDetId;
                        logs.Add(new TLog()
                        {
                            ActionType = 6,
                            CreateDate = DateTime.Now,
                            Description = "查询不到的出库单id为" + OrderDTO.orderDetId,
                            LogType = 1,
                        });
                        return false;
                    }

                    var lockCell = Context.TShippingLockCells.FirstOrDefault(s => s.OrderDetailId == shippingOrder.Id);
                    if (lockCell == null)
                    {
                        tran.Rollback();
                        errorMsg = "仓位锁定表查询失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "仓位锁定表查询失败,OrderDetailId:"+shippingOrder.Id,
                            LogType = 1,
                        });
                        return false;
                    }
                    var inv = Context.TInventories.FirstOrDefault(s => s.LocationCode==lockCell.CellCode);
                    if (inv == null)
                    {
                        tran.Rollback();
                        errorMsg = "库存查询失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "库存查询失败,CellCode:" + lockCell.CellCode,
                            LogType = 1,
                        });
                        return false;
                    }
                    if (inv.AvailableQty > lockCell.OutQty)
                    {
                        inv.AvailableQty -= lockCell.OutQty;
                        Context.Update(inv);
                    }
                    else if (inv.AvailableQty == lockCell.OutQty)
                    {
                        Context.Remove(inv);
                    }
                    else 
                    {
                        tran.Rollback();
                        errorMsg = "出库数量有误,出库数量不能大于库存数量";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "出库数量有误,出库数量不能大于库存数量,invId:" + inv.Id,
                            LogType = 1,
                        });
                        return false;
                    }
                    lockCell.IsPicking = true;
                    Context.Update(lockCell);
                    if (Context.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "系统错误，库存更改失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "系统错误，库存更改失败,invId:" + inv.Id,
                            LogType = 1,
                        });
                        return false;
                    }

                    //解绑托盘 如果托盘上没有物料了 则解绑托盘
                    var invSums = Context.TInventories.Where(s=>s.PalletBarcode==inv.PalletBarcode).Sum(s=>s.AvailableQty);
                    if (invSums <= 0)
                    {
                        var tStackingStorages = Context.TStackingStorages.Where(s => s.PalletBarcode == inv.PalletBarcode && s.Status == 1 && s.cellId == inv.LocationId).ToList();
                        if (tStackingStorages == null || tStackingStorages.Count() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "系统错误，托盘查询不到";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "系统错误，托盘查询不到,托盘条码:" + inv.PalletBarcode,
                                LogType = 1,
                            });
                            return false;
                        }
                        foreach (var tStackingStorage in tStackingStorages)
                        {
                            tStackingStorage.Status = 0;
                            Context.Update(tStackingStorage);
                            if (Context.SaveChanges() <= 0)
                            {
                                tran.Rollback();
                                errorMsg = "系统错误，托盘解绑失败";
                                logs.Add(new TLog()
                                {
                                    ActionType = 0,
                                    CreateDate = DateTime.Now,
                                    Description = "系统错误，托盘解绑失败,托盘条码:" + inv.PalletBarcode,
                                    LogType = 1,
                                });
                                return false;
                            }
                        }
                        //修改仓位状态为空仓
                        var cellObj = Context.TCells.FirstOrDefault(s => s.Code == lockCell.CellCode);
                        if (cellObj == null)
                        {
                            errorMsg = "仓位寻找失败";
                            return false;
                        }
                        cellObj.FullStatus = 0;
                        Context.Update(cellObj);
                        if (Context.SaveChanges() <= 0)
                        {
                            errorMsg = "系统错误，仓位状态修改失败";
                            return false;
                        }
                    }
                    

                    //库存流水添加
                    TInventoryLog inventoryLog = new TInventoryLog()
                    {
                        SourceType = 1,
                        SourceSn = shippingOrder.OrderSn,
                        WarehouseId = shippingOrder.WarehouseId,
                        WarehouseName= shippingOrder.WarehouseName,
                        AreaName=shippingOrder.AreaName,
                        LocationCode=inv.LocationCode,
                        MaterialId=inv.MaterialId,
                        MaterialCode=inv.MaterialCode,
                        MaterialName=inv.MaterialName,
                        BatchNo=inv.BatchNo,
                        StartQty=lockCell.InventoryQty,
                        ChangeQty= lockCell.OutQty,
                        EndQty= lockCell.InventoryQty- lockCell.OutQty,
                        CreateDate= DateTime.Now,
                        CreateUser=OrderDTO.createUser,
                        CreateUserId=OrderDTO.createUserld
                    };
                    Context.TInventoryLogs.Add(inventoryLog);
                    if (Context.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "系统错误，库存流水添加失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "系统错误，库存流水添加失败",
                            LogType = 1,
                        });
                        return false;
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    errorMsg = ex.Message;
                    logs.Add(new TLog()
                    {
                        ActionType = 6,
                        CreateDate = DateTime.Now,
                        Description = "catch:"+ex.Message,
                        LogType = 1,
                    });
                    return false;
                }
            }
        }

        /// <summary>
        /// logs不应该写成list   现在已经将错就错了  只用这个就可以
        /// </summary>
        /// <param name="OrderDTO"></param>
        /// <param name="errorMsg"></param>
        /// <param name="logs"></param>
        /// <returns></returns>
        public bool ChukuMsgNoNet(SubmitOutListDTONoNet OrderDTO, out string errorMsg, out List<TLog> logs)
        {
            errorMsg = string.Empty;
            logs = new List<TLog>();
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    // 出库复核 修改出库单为复核 和已完成
                    var shippingOrder = Context.TShippingOrderDetails.Where(s => s.Id == OrderDTO.orderDetId).FirstOrDefault();
                    if (shippingOrder != null)
                    {
                        shippingOrder.IsOutOrderReview = true;
                        shippingOrder.Status = 4;
                        Context.Update(shippingOrder);
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "修改出库单为复核失败";
                            logs.Add(new TLog()
                            {
                                ActionType = 6,
                                CreateDate = DateTime.Now,
                                Description = "修改出库单为复核失败",
                                LogType = 1,
                            });
                            return false;
                        }
                    }
                    else
                    {
                        tran.Rollback();
                        errorMsg = "查询不到的出库单id为" + OrderDTO.orderDetId;
                        logs.Add(new TLog()
                        {
                            ActionType = 6,
                            CreateDate = DateTime.Now,
                            Description = "查询不到的出库单id为" + OrderDTO.orderDetId,
                            LogType = 1,
                        });
                        return false;
                    }
                    //仓位锁定表
                    var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == shippingOrder.Id).FirstOrDefault();
                    if (lockCell == null)
                    {
                        tran.Rollback();
                        errorMsg = "仓位锁定表查询失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "仓位锁定表查询失败,OrderDetailId:" + shippingOrder.Id,
                            LogType = 1,
                        });
                        return false;
                    }
                   
                    //库存表修改
                    var inv = Context.TInventories.Where(s => s.LocationCode == lockCell.CellCode && s.MaterialCode==lockCell.MaterialCode).FirstOrDefault();
                    if (inv == null)
                    {
                        tran.Rollback();
                        errorMsg = "库存查询失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "库存查询失败,CellCode:" + lockCell.CellCode,
                            LogType = 1,
                        });
                        return false;
                    }
                    if (inv.AvailableQty > lockCell.OutQty)
                    {
                        inv.AvailableQty -= lockCell.OutQty;
                        Context.Update(inv);
                    }
                    else if (inv.AvailableQty == lockCell.OutQty)
                    {
                        Context.Remove(inv);
                    }
                    else
                    {
                        tran.Rollback();
                        errorMsg = "出库数量有误,出库数量不能大于库存数量";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "出库数量有误,出库数量不能大于库存数量,invId:" + inv.Id,
                            LogType = 1,
                        });
                        return false;
                    }
                    lockCell.IsPicking = true;
                    Context.Update(lockCell);
                    if (Context.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "系统错误，库存更改失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "系统错误，库存更改失败,invId:" + inv.Id,
                            LogType = 1,
                        });
                        return false;
                    }
                    //解绑托盘 如果托盘上没有物料了 则解绑托盘
                    var invSums = Context.TInventories.Where(s => s.PalletBarcode == inv.PalletBarcode).Sum(s => s.AvailableQty);
                    if (invSums <= 0)
                    {
                        var tStackingStorage = Context.TStackingStorages.FirstOrDefault(s => s.PalletBarcode == inv.PalletBarcode && s.Status == 1);
                        if (tStackingStorage == null)
                        {
                            tran.Rollback();
                            errorMsg = "系统错误，托盘查询不到";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "系统错误，托盘查询不到,托盘条码:" + inv.PalletBarcode,
                                LogType = 1,
                            });
                            return false;
                        }
                        tStackingStorage.Status = 0;
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "系统错误，托盘解绑失败";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "系统错误，托盘解绑失败,托盘条码:" + inv.PalletBarcode,
                                LogType = 1,
                            });
                            return false;
                        }
                    }

                    //库存流水添加
                    TInventoryLog inventoryLog = new TInventoryLog()
                    {
                        SourceType = 1,
                        SourceSn = shippingOrder.OrderSn,
                        WarehouseId = shippingOrder.WarehouseId,
                        WarehouseName = shippingOrder.WarehouseName,
                        AreaName = shippingOrder.AreaName,
                        LocationCode = inv.LocationCode,
                        MaterialId = inv.MaterialId,
                        MaterialCode = inv.MaterialCode,
                        MaterialName = inv.MaterialName,
                        BatchNo = inv.BatchNo,
                        StartQty = lockCell.InventoryQty,
                        ChangeQty = lockCell.OutQty,
                        EndQty = lockCell.InventoryQty - lockCell.OutQty,
                        CreateDate = DateTime.Now,
                        CreateUser = OrderDTO.createUser,
                        CreateUserId = OrderDTO.createUserld
                    };
                    Context.TInventoryLogs.Add(inventoryLog);
                    if (Context.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        errorMsg = "系统错误，库存流水添加失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "系统错误，库存流水添加失败",
                            LogType = 1,
                        });
                        return false;
                    }
                    
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    errorMsg = ex.Message;
                    logs.Add(new TLog()
                    {
                        ActionType = 6,
                        CreateDate = DateTime.Now,
                        Description = "catch:" + ex.Message,
                        LogType = 1,
                    });
                    return false;
                }
            }
        }
        /// <summary>
        /// logs不应该写成list   现在已经将错就错了  只用这个就可以
        /// </summary>
        /// <param name="OrderDTO"></param>
        /// <param name="errorMsg"></param>
        /// <param name="logs"></param>
        /// <returns></returns>
        public bool ChukuMsgNew(SubmitOutListDTONoNet OrderDTO, out string errorMsg, out List<TLog> logs)
        {
            errorMsg = string.Empty;
            logs = new List<TLog>();
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    // 出库复核 修改出库单为复核 和已完成
                    var shippingOrder = Context.TShippingOrderDetails.Where(s => s.Id == OrderDTO.orderDetId).FirstOrDefault();
                    if (shippingOrder != null)
                    {
                        shippingOrder.IsOutOrderReview = true;
                        shippingOrder.Status = 4;
                        Context.Update(shippingOrder);
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "修改出库单为复核失败";
                            logs.Add(new TLog()
                            {
                                ActionType = 6,
                                CreateDate = DateTime.Now,
                                Description = "修改出库单为复核失败",
                                LogType = 1,
                            });
                            return false;
                        }
                    }
                    else
                    {
                        tran.Rollback();
                        errorMsg = "查询不到的出库单id为" + OrderDTO.orderDetId;
                        logs.Add(new TLog()
                        {
                            ActionType = 6,
                            CreateDate = DateTime.Now,
                            Description = "查询不到的出库单id为" + OrderDTO.orderDetId,
                            LogType = 1,
                        });
                        return false;
                    }
                    //仓位锁定表
                    var lockCellList = Context.TShippingLockCells.Where(s => s.OrderDetailId == shippingOrder.Id).ToList();
                    if (lockCellList == null || lockCellList.Count()<=0)
                    {
                        tran.Rollback();
                        errorMsg = "仓位锁定表查询失败";
                        logs.Add(new TLog()
                        {
                            ActionType = 0,
                            CreateDate = DateTime.Now,
                            Description = "仓位锁定表查询失败,OrderDetailId:" + shippingOrder.Id,
                            LogType = 1,
                        });
                        return false;
                    }

                    foreach (var lockCell in lockCellList)
                    {
                        //库存表修改
                        var inv = Context.TInventories.Where(s => s.LocationCode == lockCell.CellCode && s.MaterialCode==lockCell.MaterialCode).FirstOrDefault();
                        if (inv == null)
                        {
                            tran.Rollback();
                            errorMsg = "库存查询失败";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "库存查询失败,CellCode:" + lockCell.CellCode,
                                LogType = 1,
                            });
                            return false;
                        }
                        if (inv.AvailableQty > lockCell.OutQty)
                        {
                            inv.AvailableQty -= lockCell.OutQty;
                            Context.Update(inv);
                        }
                        else if (inv.AvailableQty == lockCell.OutQty)
                        {
                            Context.Remove(inv);
                        }
                        else
                        {
                            tran.Rollback();
                            errorMsg = "出库数量有误,出库数量不能大于库存数量";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "出库数量有误,出库数量不能大于库存数量,invId:" + inv.Id,
                                LogType = 1,
                            });
                            return false;
                        }
                        lockCell.IsPicking = true;
                        Context.Update(lockCell);
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "系统错误，库存更改失败";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "系统错误，库存更改失败,invId:" + inv.Id,
                                LogType = 1,
                            });
                            return false;
                        }
                        
                        //库存流水添加
                        TInventoryLog inventoryLog = new TInventoryLog()
                        {
                            SourceType = 1,
                            SourceSn = shippingOrder.OrderSn,
                            WarehouseId = shippingOrder.WarehouseId,
                            WarehouseName = shippingOrder.WarehouseName,
                            AreaName = shippingOrder.AreaName,
                            LocationCode = inv.LocationCode,
                            MaterialId = inv.MaterialId,
                            MaterialCode = inv.MaterialCode,
                            MaterialName = inv.MaterialName,
                            BatchNo = inv.BatchNo,
                            StartQty = lockCell.InventoryQty,
                            ChangeQty = lockCell.OutQty,
                            EndQty = lockCell.InventoryQty - lockCell.OutQty,
                            CreateDate = DateTime.Now,
                            CreateUser = OrderDTO.createUser,
                            CreateUserId = OrderDTO.createUserld
                        };
                        Context.TInventoryLogs.Add(inventoryLog);
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "系统错误，库存流水添加失败";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "系统错误，库存流水添加失败",
                                LogType = 1,
                            });
                            return false;
                        }
                    }
                    //解绑托盘 如果托盘上没有物料了 则解绑托盘
                    var invSums = Context.TInventories.Where(s => s.PalletBarcode == lockCellList[0].PalletBarcode).Sum(s => s.AvailableQty);
                    if (invSums <= 0)
                    {
                        var tStackingStorage = Context.TStackingStorages.FirstOrDefault(s => s.PalletBarcode == lockCellList[0].PalletBarcode && s.Status == 1);
                        if (tStackingStorage == null)
                        {
                            tran.Rollback();
                            errorMsg = "系统错误，托盘查询不到";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "系统错误，托盘查询不到,托盘条码:" + lockCellList[0].PalletBarcode,
                                LogType = 1,
                            });
                            return false;
                        }
                        tStackingStorage.Status = 0;
                        if (Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            errorMsg = "系统错误，托盘解绑失败";
                            logs.Add(new TLog()
                            {
                                ActionType = 0,
                                CreateDate = DateTime.Now,
                                Description = "系统错误，托盘解绑失败,托盘条码:" + lockCellList[0].PalletBarcode,
                                LogType = 1,
                            });
                            return false;
                        }
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    errorMsg = ex.Message;
                    logs.Add(new TLog()
                    {
                        ActionType = 6,
                        CreateDate = DateTime.Now,
                        Description = "catch:" + ex.Message,
                        LogType = 1,
                    });
                    return false;
                }
            }
        }
    }
}
